package com.tgy.leetcode;

/**
 * @Author: tgy
 * @Date: 2020/11/29 10:25 下午
 */
public class _19_删除链表的倒数第N个节点 {

    public ListNode removeNthFromEnd(ListNode head, int n) {

        if (head == null || n <= 0) {

            return null;
        }

        ListNode nodeHead = new ListNode();
        nodeHead.next = head;
        ListNode removeNode = null;
        int index = 0;
        while (head != null) {

            if (index == n - 1) {

                removeNode = nodeHead;
            }else if (index >= n) {

                removeNode = removeNode.next;
            }

            index++;
            head = head.next;
        }

        if (removeNode != null) {

            removeNode.next = removeNode.next.next;
        }

        return nodeHead.next;
    }
}
